package cn.cellcom.agent.biz;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.j2ee.AgentListener;
import cn.cellcom.agent.online.client.IDManager;
import cn.cellcom.agent.pojo.TButton;
import cn.cellcom.agent.pojo.TChannel;
import cn.cellcom.agent.pojo.TCrmField;
import cn.cellcom.agent.pojo.TCrmFieldOption;
import cn.cellcom.agent.pojo.TGroup;
import cn.cellcom.agent.pojo.TGroupUser;
import cn.cellcom.agent.pojo.TOrg;
import cn.cellcom.agent.pojo.TQuestion;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.TUserForm;
import cn.cellcom.agent.util.RedisManager;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.reflect.ToString;
import cn.cellcom.jar.util.CU;
import cn.cellcom.jar.util.CopyUtil;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.IDGenerator;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;
import cn.cellcom.jar.util.PinyinUtil;

public class TUserBiz extends AbstractBiz {

	@Override
	public List delete(HttpServletRequest req, ActionForm form, Object obj) {

		return null;
	}

	@Override
	public Object add(HttpServletRequest req, ActionForm form, Object obj) {
		TUserForm fm = (TUserForm) form;
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		try {
			log.info("add log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String no = fm.getNo();
			// 你必须修改这里的id值
			if (no != null
					&& this.getDao().myGet("from " + TUser.class.getSimpleName() + " where (no=? and pid=?) or (username=?)",
							new String[] { no, user.getPid(), fm.getUsername() }) != null) {
				return "用户名或者企业内工号已经存在，不要重复添加";
			}
			TUser pojo = new TUser();
			CopyUtil.copy(req, pojo, null, false);
			pojo.setOrg(user.getOrg());
			pojo.setPid(user.getPid());
			pojo.setInsertTime(DT.getNow());

			this.getDao().mySave(pojo);

			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "新增数据出现错误", e);
		}
	}

	@Override
	public Object modify(HttpServletRequest req, ActionForm form, Object obj) {
		TUserForm fm = (TUserForm) form;
		LogonSession ls = new LogonSession(req);
		try {
			log.info("modify log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String key = fm.getUsername();
			TUser pojo = (TUser) this.getDao().myGet(TUser.class, key);
			if (pojo == null) {
				return "修改的记录不存在";
			}
			log.info("被修改的pojo：" + ToString.toString(TUser.class, pojo, false));

			// 以下为pojo的必填字段
			CopyUtil.copy(req, pojo, null, false);

			this.getDao().myUpdate(pojo);

			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "修改数据出现错误", e);
		}

	}

	/**
	 * 查询指定的坐席
	 * 
	 * @param pid
	 * @param type
	 * @param status
	 * @return
	 * @throws MyException
	 */
	public List<TUser> getAgents(String pid, String type, String status) throws MyException {
		String hql = "from " + TUser.class.getSimpleName() + " where pid=? and type=? and status=? order by username";
		String[] values = new String[] { pid, type, status };
		if (StringUtils.isBlank(type)) {
			hql = "from " + TUser.class.getSimpleName() + " where pid=? and status=? order by username";
			values = new String[] { pid, status };
		}
		return this.getDao().myList(hql, values);
	}

	/**
	 * 注册账号
	 * 
	 * @param email
	 * @param phone
	 * @param username
	 * @param orgName
	 * @param password
	 * @return
	 * @throws MyException
	 */
	public Object register(String orgName, String username, String phone, String email, String password, String ip) throws MyException {
		String orgCode = "jianyue".equals(orgName) || "jianyuekefu".equals(orgName) ? orgName : PinyinUtil.getFullAtStr(orgName) + CU.getRand(5);
		TUser user = new TUser();
		user.setEmail(email);
		user.setInsertTime(DT.getNow());
		user.setLevel(AgentConstant.USER_DEFAULT_LEVEL);
		user.setUsername(username);
		user.setNickName(orgName);// 采用企业作为昵称吧
		user.setName("管理员");
		user.setNo(AgentConstant.DEFAULT_NO);
		user.setOrg(orgCode);
		user.setPid(orgCode);
		user.setPassword(password);
		user.setPhone(phone);
		user.setStatus(AgentConstant.YES);
		user.setType(AgentConstant.USER_TYPE_MANAGER);
		this.getDao().mySave(user);

		TOrg org = new TOrg();
		org.setInsertTime(DT.getNow());
		org.setName(orgName);
		org.setOrg(user.getOrg());
		org.setPid(user.getPid());
		org.setPhone(phone);
		org.setIp(ip);
		this.getDao().mySave(org);

		TChannel channel = new TChannel();
		channel.setId(IDGenerator.getDefaultUUID());
		channel.setInsertTime(DT.getNow());
		channel.setMemo("默认渠道");
		channel.setName("官方渠道");
		channel.setNo(AgentConstant.DEFAULT_NO);
		channel.setOrg(org.getOrg());
		channel.setPid(org.getPid());
		channel.setType(AgentConstant.CHANNEL_TYPE.WEB.name());
		this.getDao().mySave(channel);

		TGroup group = new TGroup();
		group.setId(IDManager.getGid());
		group.setName("服务组");
		group.setNo(AgentConstant.DEFAULT_NO);
		group.setOrg(org.getOrg());
		group.setPid(org.getPid());
		this.getDao().mySave(group);

		TGroupUser gu = new TGroupUser();
		gu.setGroupId(group.getId());
		gu.setId(IDManager.getGUid());
		gu.setOrg(user.getOrg());
		gu.setUser(user.getUsername());
		gu.setPid(org.getPid());
		gu.setSwitchPolicy(0);
		this.getDao().mySave(gu);

		/*
		 * name varchar 100 0 -1 0 0 0 0 0 gbk gbk_chinese_ci 0 0 phone varchar
		 * 100 0 -1 0 0 0 0 0 gbk gbk_chinese_ci 0 0 email varchar 100 0 -1 0 0
		 * 0 0 0 gbk gbk_chinese_ci 0 0 level int 11 0 -1 0 0 0 0 0 0 0 status
		 * int 11 0 -1 0 0 0 0 0 0 0 qq varchar 100 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 sex varchar 100 0 -1 0 0 0 0 0 gbk gbk_chinese_ci
		 * 0 0 company varchar 100 0 -1 0 0 0 0 0 gbk gbk_chinese_ci 0 0
		 * province varchar 100 0 -1 0 0 0 0 0 gbk gbk_chinese_ci 0 0 city
		 * varchar 100 0 -1 0 0 0 0 0 gbk gbk_chinese_ci 0 0 memo varchar 100 0
		 * -1 0 0 0 0 0 gbk gbk_chinese_ci 0 0 tid varchar 100 0 -1 0 0 0 0 0
		 * gbk gbk_chinese_ci 0 0 type int 11 0 0 0 0 0 0 0 0 0 create_time
		 * bigint 20 0 -1 0 0 0 0 0 0 0 extend1 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend2 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend3 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend4 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend5 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend6 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend7 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend8 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend9 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0 extend10 varchar 1000 0 -1 0 0 0 0 0 gbk
		 * gbk_chinese_ci 0 0
		 * 
		 * String id, String org, String pid, String fname, String fshowName,
		 * String ftype, Short fsystem, Short fsearch, Short fenable, Short
		 * frequied, Short fmodify, Short flist, Long createTime
		 */
		List<TCrmField> fields = new ArrayList<TCrmField>();
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "id", "ID", "H", 1, 0, 1, 0, 1, 0, System.currentTimeMillis(), 0));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "tid", "TID", "I", 1, 1, 1, 0, 0, 1, System.currentTimeMillis(), 0));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "name", "姓名", "I", 1, 1, 1, 1, 1, 1, System.currentTimeMillis(), 1));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "phone", "电话", "I", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 2));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "email", "邮箱", "I", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 3));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "level", "等级", "S", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 4));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "status", "状态", "S", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 5));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "qq", "QQ", "I", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 6));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "sex", "性别", "S", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 7));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "company", "企业", "I", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 8));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "province", "省份", "S", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 9));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "city", "城市", "S", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 10));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "memo", "备注", "T", 1, 1, 1, 0, 1, 1, System.currentTimeMillis(), 11));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "type", "类型", "S", 1, 1, 1, 0, 0, 1, System.currentTimeMillis(), 12));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "head", "头像", "H", 1, 0, 1, 0, 1, 0, System.currentTimeMillis(), 13));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend1", "扩展1", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 14));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend2", "扩展2", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 15));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend3", "扩展3", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 16));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend4", "扩展4", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 17));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend5", "扩展5", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 18));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend6", "扩展6", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 19));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend7", "扩展7", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 20));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend8", "扩展8", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 21));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend9", "扩展9", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 22));
		fields.add(new TCrmField(IDManager.getCfid(), org.getOrg(), "extend10", "扩展10", "I", 1, 0, 0, 0, 0, 0, System.currentTimeMillis(), 23));
		this.getDao().mySaveOrUpdate(fields);
		/*
		 * 1 xunhongwangluo48025 status 可用 1 222 2 xunhongwangluo48025 status 禁用
		 * 2 222 3 xunhongwangluo48025 level 普通 1 222 4 xunhongwangluo48025
		 * level 会员 2 222 5 xunhongwangluo48025 level 黄金 3 222 6
		 * xunhongwangluo48025 sex 先生 1 222 7 xunhongwangluo48025 sex 女士 2 222
		 */
		List<TCrmFieldOption> options = new ArrayList<TCrmFieldOption>();
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "status", "可用", "0", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "status", "禁用", "1", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "level", "普通", "1", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "level", "会员", "2", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "level", "黄金", "3", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "level", "红名单", "4", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "sex", "未知", "1", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "sex", "先生", "2", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "sex", "女士", "3", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "type", "匿名访问", "1", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "type", "对接获取", "2", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "type", "主动注册", "3", System.currentTimeMillis()));
		options.add(new TCrmFieldOption(IDGenerator.getDefaultUUID(), org.getOrg(), "type", "系统增加", "4", System.currentTimeMillis()));

		this.getDao().mySaveOrUpdate(options);

		TButton button = new TButton();
		button.setHref("http://www.jianyuekefu.com:8080");
		button.setId(IDGenerator.getDefaultUUID());
		button.setImg("jianyue.png");
		button.setName("简约客服");
		button.setOrg(user.getOrg());
		button.setPid(user.getPid());
		button.setSeq(RedisManager.getInstance().getButtonNo(user.getPid()));
		button.setTitle("这个按钮可以跳转到简约客服");
		button.setMemo("注册时产生的测试按钮");
		button.setSubject(AgentConstant.DEFAULT_ORG);
		this.getDao().mySave(button);

		// 初始化一下提问题
		try {
			initQuestion(user, orgName);
		} catch (Exception e) {
			log.error("", e);
		}
		return Env.SUCCESS;
	}

	private void initQuestion(TUser user, String orgName) throws MyException {
		TQuestion pojo = new TQuestion();
		pojo.setId(IDManager.getQid());
		pojo.setOrg(user.getOrg());
		pojo.setPid(user.getPid());
		pojo.setNo(String.valueOf(RedisManager.getInstance().getQuestionNo(user.getPid())));
		pojo.setInsertTime(DT.getYYYYMMDDHHMMSS());
		pojo.setQuestion("贵企业叫什么？");
		pojo.setAnswer(orgName);
		pojo.setType(AgentConstant.QUESTION_TYPE.F.name());
		pojo.setTimes(0);
		pojo.setSubject(AgentConstant.DEFAULT_ORG);
		AgentListener.getMgDao().mySave(pojo);

		TQuestion pojo2 = new TQuestion();
		pojo2.setId(IDManager.getQid());
		pojo2.setOrg(user.getOrg());
		pojo2.setPid(user.getPid());
		pojo2.setNo(String.valueOf(RedisManager.getInstance().getQuestionNo(user.getPid())));
		pojo2.setInsertTime(DT.getYYYYMMDDHHMMSS());
		pojo2.setQuestion("贵企业的联系电话是多少");
		pojo2.setAnswer(user.getPhone());
		pojo2.setType(AgentConstant.QUESTION_TYPE.F.name());
		pojo2.setTimes(0);
		pojo2.setSubject(AgentConstant.DEFAULT_ORG);
		AgentListener.getMgDao().mySave(pojo2);

		TQuestion pojo3 = new TQuestion();
		pojo3.setId(IDManager.getQid());
		pojo3.setOrg(user.getOrg());
		pojo3.setPid(user.getPid());
		pojo3.setNo(String.valueOf(RedisManager.getInstance().getQuestionNo(user.getPid())));
		pojo3.setInsertTime(DT.getYYYYMMDDHHMMSS());
		pojo3.setQuestion("你好，您好，HELLO");
		pojo3.setAnswer("您好，请问有什么可以帮您？");
		pojo3.setType(AgentConstant.QUESTION_TYPE.B.name());
		pojo3.setTimes(0);
		pojo3.setSubject(AgentConstant.DEFAULT_ORG);
		AgentListener.getMgDao().mySave(pojo3);

		TQuestion pojo4 = new TQuestion();
		pojo4.setId(IDManager.getQid());
		pojo4.setOrg(user.getOrg());
		pojo4.setPid(user.getPid());
		pojo4.setNo(String.valueOf(RedisManager.getInstance().getQuestionNo(user.getPid())));
		pojo4.setInsertTime(DT.getYYYYMMDDHHMMSS());
		pojo4.setQuestion("如何让网站嵌入这个访客端页面?");
		pojo4.setAnswer("请将这段代码嵌入到您的网站&lt;script type='text/javascript' src='http://wwww.jianyuekefu/js/online/visitor-access.js?pid=" + user.getPid()
				+ "&channel=10001'&gt;&lt;/script&gt;");
		pojo4.setType(AgentConstant.QUESTION_TYPE.F.name());
		pojo4.setTimes(0);
		pojo4.setSubject(AgentConstant.DEFAULT_ORG);
		AgentListener.getMgDao().mySave(pojo4);

		TQuestion pojo5 = new TQuestion();
		pojo5.setId(IDManager.getQid());
		pojo5.setOrg(user.getOrg());
		pojo5.setPid(user.getPid());
		pojo5.setNo(String.valueOf(RedisManager.getInstance().getQuestionNo(user.getPid())));
		pojo5.setInsertTime(DT.getYYYYMMDDHHMMSS());
		pojo5.setQuestion("界面为什么有这些问号?");
		pojo5.setAnswer("您通过体验方式进入，所以系统会呈现问号做引导提示，正常嵌入代码使用客服系统不会呈现这些问号的");
		pojo5.setType(AgentConstant.QUESTION_TYPE.F.name());
		pojo5.setTimes(0);
		pojo5.setSubject(AgentConstant.DEFAULT_ORG);
		AgentListener.getMgDao().mySave(pojo5);

		TQuestion pojo6 = new TQuestion();
		pojo6.setId(IDManager.getQid());
		pojo6.setOrg(user.getOrg());
		pojo6.setPid(user.getPid());
		pojo6.setNo(String.valueOf(RedisManager.getInstance().getQuestionNo(user.getPid())));
		pojo6.setInsertTime(DT.getYYYYMMDDHHMMSS());
		pojo6.setQuestion("有更多问题怎么办?");
		pojo6.setAnswer("您可以加微信或者拨打电话:13570254864<br/><a href='../file/load.do?method=get&bizType=SETTING&fileName=功能手册.xlsx&name=功能手册.xlsx'>下载功能[功能手册]文档</a>");
		pojo6.setType(AgentConstant.QUESTION_TYPE.F.name());
		pojo6.setTimes(0);
		pojo6.setSubject(AgentConstant.DEFAULT_ORG);
		AgentListener.getMgDao().mySave(pojo6);
	}

	/**
	 * 
	 * @param username
	 * @param phone
	 * @param email
	 * @return
	 * @throws MyException
	 */
	public TUser get(String username, String phone) throws MyException {
		String hql = "from " + TUser.class.getSimpleName() + " where username=? or phone = ?";
		return (TUser) this.getDao().myGet(hql, new String[] { username, phone });
	}

	/**
	 * 
	 * @param org
	 * @param groupId
	 * @return
	 */
	public List<TGroup> getGroups(String user) throws MyException {
		String hql = "select a from " + TGroup.class.getSimpleName() + " as a, " + TGroupUser.class.getSimpleName()
				+ " as b where a.id=b.groupId and b.user=? order by a.id";
		String[] values = new String[] { user };
		return this.getDao().myList(hql, values);
	}
}
